//
// Created by gogoqiu on 2022/2/14.
//

#include "wxPrintFrame.h"
#include "Printout.h"

BEGIN_EVENT_TABLE ( wxPrintFrame, wxFrame )
                //EVT_MENU ( ACTION_EVENT, PreferencesFrame::OnActionEvent )
                EVT_BUTTON ( ID_BUTTON_SETUP, wxPrintFrame::OnPrintSetupClicked )
                EVT_BUTTON ( ID_BUTTON_PRINT, wxPrintFrame::OnPrintClicked )
                EVT_BUTTON ( ID_BUTTON_PREVIEW, wxPrintFrame::OnPrintPreviewClicked )
END_EVENT_TABLE()

wxPrintData *g_printData = nullptr;
wxPageSetupDialogData* g_pageSetupData = nullptr;

void wxPrintFrame::OnPrintSetupClicked(wxCommandEvent &event) {
    (*g_pageSetupData) = *g_printData;

    wxPageSetupDialog pageSetupDialog(this, g_pageSetupData);
    pageSetupDialog.ShowModal();

    (*g_printData) = pageSetupDialog.GetPageSetupDialogData().GetPrintData();
    (*g_pageSetupData) = pageSetupDialog.GetPageSetupDialogData();
}

void wxPrintFrame::OnPrintClicked(wxCommandEvent &event) {
    wxPrintDialogData printDialogData(* g_printData);

    wxPrinter printer(&printDialogData);
    Printout po(this, wxT("My printout"));
    if (!printer.Print(this, &po, true /*prompt*/))
    {
        if (wxPrinter::GetLastError() == wxPRINTER_ERROR){
            wxMessageBox(wxT("There was a problem printing. Perhaps your current printer is not set correctly?"));
        }else{
            wxMessageBox(wxT("You canceled printing"));
        }
    }else{
        (*g_printData) = printer.GetPrintDialogData().GetPrintData();
    }
}

void wxPrintFrame::OnPrintPreviewClicked(wxCommandEvent &event) {
    auto *preview =new wxPrintPreview(new Printout(this),
                                      new Printout(this), g_printData);
    if (!preview->IsOk()){
        delete preview;
        wxMessageBox(_T("There was a problem previewing"),_T("打印预览"),wxOK);
        return;
    }
    auto *frame =new wxPreviewFrame(preview, this, wxT("打印预览实例"), wxPoint(100, 100), wxSize(600, 650));
    frame->Centre(wxBOTH);
    frame->Initialize();
    frame->Show();
}

//
wxPrintFrame::wxPrintFrame( wxWindow* parent ): wxFrame( parent, wxID_ANY, "" ) {
    g_printData = new wxPrintData;
    g_pageSetupData = new wxPageSetupDialogData;
    auto * sizer = new wxBoxSizer( wxHORIZONTAL );
    //
    bt_setup = new wxButton( this, ID_BUTTON_SETUP, "SETUP" );
    bt_print = new wxButton( this, ID_BUTTON_PRINT, "PRINT" );
    bt_preview = new wxButton( this, ID_BUTTON_PREVIEW, "PREVIEW" );
    sizer->Add( bt_preview );
    sizer->Add( bt_print );
    sizer->Add( bt_setup );
    SetSizer( sizer );
}

wxPrintFrame::~wxPrintFrame() {
    delete g_printData;
    delete g_pageSetupData;
}
